package com.stylefeng.guns.rest.modular.wz.api.back;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWz;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.controller.TextScanService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzAdvServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 新闻模块
 */
@RestController
@RequestMapping("/wz/api/v4/news/")
public class WzNewsV4Api extends ApiBaseController {
    @Autowired
    private WzNewsMapper newsMapper;
    @Autowired
    private WzUserAdvCollectionMapper userAdvCollectionMapper;
    @Autowired
    private WzAdvCommentMapper advCommentMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private PfReportMapper reportMapper;
    @Autowired
    private WzAdvServiceImpl advService;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzNewsUninterestedMapper newsUninterestedMapper;
    @Autowired
    private WzNewsCommentLikeMapper newsCommentLikeMapper;
    @Autowired
    private WzRedpacketCommentMapper redpacketCommentMapper;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private TextScanService textScanService;
    @Autowired
    private AsyncService asyncService;


    /**
     * 新闻评论列表
     */
    @PostMapping("commentList")
    public Res commentList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advId = paramMap.getLongMisValid("advId");
        Long userCode = paramMap.getLong("userCode");
        int type = paramMap.getIntMisValid("type");
        String advCommentsSql = "status,main_user_code As mainUserCode,reply_number As replyNumber,has_user_comment As hasUserComment,is_like As isLike,like_number As likeNumber,adv_comment_id As advCommentId,user_code As userCode,content,nick_name As nickName,avatar_url As avatarUrl,create_time As createTime";
        EntityWrapper entityWrapper = new EntityWrapper();
        if(type == 1){//按热度排序 like_number
            entityWrapper.setSqlSelect(advCommentsSql).eq("adv_id",advId).isNull("reply_user_code").orderBy("like_number",false).orderBy("create_time",false);
        }else if(type == 2){//按时间排序
            entityWrapper.setSqlSelect(advCommentsSql).eq("adv_id",advId).isNull("reply_user_code").orderBy("create_time",false).orderBy("like_number",false);
        }
        List<Map<String,Object>>  advComments = advCommentMapper.selectMapsPage(new Page<>(pageNum,pageSize),entityWrapper);
        for(Map<String,Object> map:advComments){
            if(userCode != null){
                int c = newsCommentLikeMapper.selectCount(new EntityWrapper<WzNewsCommentLike>().eq("adv_comment_id",Long.parseLong(map.get("advCommentId").toString())).eq("user_code",userCode));
                if(c > 0){
                    map.put("isLike",1);
                }
            }
            if(Integer.parseInt(map.get("hasUserComment").toString()) != 0){
                if(map.get("mainUserCode") == null){
                    List<Map<String,Object>> replyList = new ArrayList<>();
                    map.put("replyList",replyList);
                }else{
                    List<Map<String,Object>> replyList = advCommentMapper.selectMapsPage(new Page<>(1,5),new EntityWrapper<WzAdvComment>().isNotNull("reply_user_code").eq("adv_id",advId).eq("main_user_code",Long.parseLong(map.get("mainUserCode").toString())).orderBy("create_time",false));
                    map.put("replyList",replyList);
                }
            }else{
                List<Map<String,Object>> replyList = new ArrayList<>();
                map.put("replyList",replyList);
            }
        }
        return Res.success(paramMap.data(advComments));
    }

    /**
     * 增加新闻评论
     */
    @PostMapping("commentAdd")
    public Res commentAdd(@RequestBody ParamMap paramMap) throws Exception{
        Long advId = paramMap.getLongMisValid("advId");
        String content = paramMap.getStrMisValid("content");
        Long replyUserCode = paramMap.getLongValid("replyUserCode");
//        boolean r = textScanService.textScan(content);
//        if(!r){
//            return Res.fail("请文明评论!");
//        }
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        WzUser myUser = cacheService.user(userCode);
        if(myUser.getStatus() == 0){
            return Res.fail("账户冻结中!");
        }
        WzAdvComment mainAdvComment = null;
        WzUser pushUser = null;
        String pushContent = "尊敬的用户，您有发布的爆料有一个新评论，去看看吧!";
        String pushTitle = "您的爆料有新评论!";
        //新建评论
        WzAdvComment advComment = new WzAdvComment();
        advComment.setAdvCommentId(IdWorker.getId());
        advComment.setAdvId(advId);
        advComment.setAvatarUrl(myUser.getAvatarUrl());
        advComment.setContent(content);
        advComment.setCreateTime(new Date());
        advComment.setUserCode(userCode);
        if(replyUserCode == null){//评论
            advComment.setNickName(myUser.getNickName());
            advComment.setMainUserCode(advComment.getAdvCommentId());
            WzNews news = newsMapper.selectById(advId);
            pushUser = cacheService.user(news.getUserCode());
            if(news.getUserCode() == null){
                pushTitle =null;
            }else{
                if(news.getUserCode().toString().equals(userCode.toString())){
                    pushTitle =null;
                }
            }
        }else{//回复
            Long advCommentId = paramMap.getLongMisValid("advCommentId");
            WzAdvComment oldAdvComment = advCommentMapper.selectById(advCommentId);//上条回复
            if(oldAdvComment == null){
                return Res.fail(BizExceptionEnum.NEWS_SHIXIAO);
            }
            if(oldAdvComment.getMainUserCode() == null && oldAdvComment.getReplyUserCode() == null){
                oldAdvComment.setMainUserCode(oldAdvComment.getAdvCommentId());
            }
            WzUser replyUser = cacheService.user(replyUserCode);
            pushUser = replyUser;
            if (oldAdvComment.getMainUserCode().toString().equals(userCode.toString())) {//主回复人回复
                advComment.setNickName(myUser.getNickName() +" 回复 "+replyUser.getNickName());
                pushContent = "尊敬的用户，您的一个爆料评论有新回复，去看看吧!";
                pushTitle = "您的一个爆料评论有新回复!";
            }else if(oldAdvComment.getMainUserCode().toString().equals(oldAdvComment.getAdvCommentId().toString())){//用户回复主回复人
                advComment.setNickName(myUser.getNickName());
                pushContent = "尊敬的用户，您的一个爆料评论有新回复，去看看吧!";
                pushTitle = "您的一个爆料评论有新回复!";
            }else{//用户回复用户
                advComment.setNickName(myUser.getNickName() +" 回复 "+replyUser.getNickName());
            }
            advComment.setMainUserCode(oldAdvComment.getMainUserCode());
            advComment.setReplyUserCode(replyUserCode);
            if(oldAdvComment.getReplyUserCode() == null){
                mainAdvComment = oldAdvComment;
            }else{
                List<WzAdvComment> advComments = advCommentMapper.selectList(new EntityWrapper<WzAdvComment>().eq("adv_id",advId).isNull("reply_user_code").eq("main_user_code",oldAdvComment.getMainUserCode()));
                mainAdvComment = advComments.get(0);
            }
            mainAdvComment.setHasUserComment(1);
            mainAdvComment.setReplyNumber(mainAdvComment.getReplyNumber() +1);
        }
        int rr = advCommentMapper.insert(advComment);
        if(rr > 0){
            WzNews news = newsMapper.selectById(advId);
            news.setReleaseTime(new Date());
            rr = newsMapper.updateById(news);
            if(rr > 0){
                if(mainAdvComment != null){
                    rr = advCommentMapper.updateById(mainAdvComment );
                    if(rr <= 0){
                        return Res.fail();
                    }
                }
                if(StringUtils.isNotBlank(pushTitle)){
                    //异步发送结果
                    WzUserMessage userMessage = new WzUserMessage();//用户消息
                    userMessage.setCreateTime(new Date());
                    userMessage.setType(EnWz.User_Message_News_Comment.getIndex());//新闻评论推送
                    userMessage.setUserCode(news.getUserCode());
                    userMessage.setContent(pushContent);
                    userMessage.setTitle(pushTitle);
                    //发送通知
                    JSONObject j = new JSONObject();
                    j.put("advId", advId);
                    asyncService.checkUserAdv(userMessage,pushUser,EnWz.User_Message_News_Comment.getIndex(),j);
                }
                return Res.success();
            }
        }
        return Res.fail();
    }

    /**
     * 回复列表
     */
    @Transactional
    @PostMapping("userCommentList")
    public Res userCommentList(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advCommentId = paramMap.getLongMisValid("advCommentId");
        Long userCode = paramMap.getLongMisValid("userCode");
        String advCommentsSql = "main_user_code As mainUserCode,reply_number As replyNumber,has_user_comment As hasUserComment,is_like As isLike,like_number As likeNumber,adv_comment_id As advCommentId,user_code As userCode,content,nick_name As nickName,avatar_url As avatarUrl,create_time As createTime";
        List<WzAdvComment>  advCommentList = advCommentMapper.selectList(new EntityWrapper<WzAdvComment>().eq("adv_comment_id",advCommentId));
        List<Map<String,Object>> advComments = advCommentMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzAdvComment>().setSqlSelect(advCommentsSql).ne("adv_comment_id",advCommentId).eq("main_user_code",advCommentId).orderBy("create_time",false));
        if(userCode != null){
            for(Map<String,Object> map:advComments){
                int c = newsCommentLikeMapper.selectCount(new EntityWrapper<WzNewsCommentLike>().eq("adv_comment_id",Long.parseLong(map.get("advCommentId").toString())).eq("user_code",userCode));
                if(c > 0){
                    map.put("isLike",1);
                }
            }
        }
        return Res.success(paramMap.data(advComments));
    }

}
